import aiofiles
import aiohttp
import hashlib
import config
import json
import os
from types import SimpleNamespace


async def move(src, dst):
    async with aiofiles.open(src, "rb") as f:
        content = await f.read()
    async with aiofiles.open(dst, "wb") as f:
        await f.write(content)

    if hasattr(config, "delete"):
        try:
            os.remove(src)
        except:
            pass


def hash(string: str):
    return hashlib.md5(string.encode("utf-8")).hexdigest()


async def download_image(url: str):
    extension = "." + url.split(".")[-1]
    filename = hash(url) + extension
    dst = config.tmp_folder / filename

    if dst.exists():
        return dst

    session = aiohttp.ClientSession()
    async with session.get(url) as res:
        content = await res.read()
    await session.close()

    # Check everything went well
    if res.status != 200:
        print(f"Download failed: {res.status}")
        return

    async with aiofiles.open(dst, "+wb") as f:
        await f.write(content)

    return dst


class Namespace(SimpleNamespace):
    def __contains__(self, key):
        return hasattr(self, key)


def parse_json(text: str):
    return json.loads(text, object_hook=lambda d: Namespace(**d))


def add_zeros(string: str, length: int):
    string = str(string)
    return "0" * (length - len(string)) + string
